import { noticeMap, setNotify, showNotify } from './helpers';
import { TtNotifyType } from './NotificationItem.vue';

/**
 * 1. 基于 Antd 的 notification 做样式覆盖；
 * 2. 包含“个人”和“平台”的通知；
 * 3. 当“个人”和“平台”分别有未读的通知时（从info接口拿未读数量），就分别去轮询这两个接口。当其中一个未读数量为0时，就不再轮询对应的接口；
 * 4. 当点击通知时，做对应通知的操作（和通知列表组件一样），并将对应通知设为已读
 * 5. 当点击通知的关闭按钮时，关闭通知弹窗，并将对应通知设为已读
 */

/** 轮询通知并弹出通知弹窗 */
export function usePollingNotifications() {
  const userStore = useUserStore();
  const personalNoticePollable = computed(() => !!userStore.userInfo?.user_notice?.personal_count);
  const platformNoticePollable = computed(() => !!userStore.userInfo?.user_notice?.platform_count);

  const time = new Date().getTime();

  const personalNotices = useQuery({
    enabled: personalNoticePollable,
    queryKey: [apis.apiNoticePersonalLIst.id],
    queryFn: () => apis.apiNoticePersonalLIst({}),
    refetchInterval: 10 * 1000,
    select(data) {
      data.list?.forEach((d) => {
        if (d.status === 2) {
          setNotify(d.notice_id, d.title, d.content, TtNotifyType.USER, { linkType: d.link_type, orderNo: d.order_no });
        }

        if (d.status === 2 && d.link_type === 16) {
          globalPopups.newUserAward?.open({ noticeId: d.notice_id });
        }
        if (d.status === 2 && d.link_type === 18) {
          globalPopups.wallet.open({ initTab: 'deposit', isDepositPage: true, checkedBonusKey: 'signUp', source: 'newUser' });
        }
        if (d.status === 2 && d.link_type === 17) {
          queryClient.invalidateQueries({ queryKey: [apis.apiActivityInviteReady.id], exact: false });
          queryClient.invalidateQueries({ queryKey: [apis.apiActivityInviteUsers.id], exact: false });
        }
      });
    },
  });
  const platformNotices = useQuery({
    enabled: platformNoticePollable,
    queryKey: [apis.apiNoticePlatformLIst.id],
    queryFn: () => apis.apiNoticePlatformLIst({}),
    refetchInterval: 10 * 1000,
    select(data) {
      data.list?.forEach((d) => {
        if (d.is_read === 2 && d.create_time > time)
          setNotify(d.notice_id, d.title, d.content, TtNotifyType.PLATEFORM, { url: d.url });
      });
    },
  });

  watch(() => noticeMap.size, (v) => {
    if (v) {
      showNotify();
    }
  });
}
